<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<body>
		<style>
			.datepicker-input{height: 34px; border: 1px solid #D3D3D3; background-color: #fff; border-radius: 2px; width: 250px; padding: 0px 4px;}
			#purchaseLogisticsEditForm .form-item , #purchase-create-storehouse-form .form-item , #purchaseDetailsEditForm .form-item , #purchaseEditForm .form-item{margin: 20px 0px;}
			#purchaseLogisticsEditForm .form-item >label , #purchase-create-storehouse-form .form-item > label , #purchaseDetailsEditForm .form-item > label , #purchaseEditForm .form-item > label{min-width: 72px; text-align: left; display: inline-block;}
			.input-file{position: absolute; left: 0px; top: 0px; display: inline-block; width: 100%; height: 30px; line-height: 30px; opacity: 0;}
			.download-link{display: inline-block; height: 30px; width: 100%;}
		</style>
		<div class="super-theme-example">
			<div class="options-toolbar">
				<form id="purchaseDatagridQueryParams">
					<input class="easyui-textbox" name="purchaseCode" data-options="width:150,prompt:'采购单号'">
					<input id="purchase-supplier-combo" name="supplierId" style="width:200px;">
					<input id="purchase-storehouseCombo" name="storehouseId" style="width:150px;">
					<select class="easyui-combobox" name="status" style="width:120px;">
					    <option value="">全部状态</option>
					    <option value="0">已创建</option>
					    <option value="10">已派单</option>
					    <option value="20">已完成</option>
					    <option value="-10">已取消</option>
					</select>
					<input class="easyui-textbox" name="comments" data-options="width:150,prompt:'备注'">
					<input class="easyui-textbox" name="logisticCode" data-options="width:150,prompt:'物流单号'">
					<input class="easyui-textbox" name="productSkuBarcode" data-options="width:150,prompt:'商品条形码'">
					<input class="easyui-textbox" name="productId" data-options="width:150,prompt:'产品编码'">
					<input id="purchase-datepicker" class="datepicker-input" />
					<a href="javascript:void(0)" class="easyui-linkbutton primary" data-options="iconCls:'fa fa-search'" onclick="purchase.methods.queryDatagrid();">查询</a>
				</form>
				<div class="top-options">
					<a href="#" class="easyui-menubutton info" data-options="menu:'#addPurchaseMenu',plain:false,hideOnUnhover:false">操作</a>
					<div id="addPurchaseMenu" class="download-btn-menu">
						<div data-options="iconCls:'fa fa-download'" onclick="exportExcel(commonConfig.mgUrlPrefix() + '/admin/purchase/list/export' , purchase.methods.initDatagridQueryParams())">导出采购单-完整数据</div>
						<div data-options="iconCls:'fa fa-download'" onclick="exportExcel(commonConfig.mgUrlPrefix() + '/admin/purchase/list/simple-export' , purchase.methods.initDatagridQueryParams())">导出采购单-基础数据</div>
						<div class="menu-sep"></div>
						<div data-options="iconCls:'fa fa-upload'">
							<span class="input-span">上传采购单</span>
							<input class="input-file" type="file" onchange="purchase.methods.addPurchase(this);this.value = null;" />
						</div>
						<div data-options="iconCls:'fa fa-file-excel-o'">
							<a class="download-link" download="" mce_href="#" href="excel/采购单模板.xlsx">下载采购单模板</a>
						</div>
						<div class="menu-sep"></div>
						<div data-options="iconCls:'fa fa-upload'">
							<span class="input-span">采购单绑定物流信息</span>
							<input class="input-file" type="file" onchange="purchase.methods.addPurchaseLogistics(this)" />
						</div>
						<div data-options="iconCls:'fa fa-file-excel-o'">
							<a class="download-link" download="" mce_href="#" href="excel/采购单绑定物流单号.xlsx">下载采购单绑定物流单号</a>
						</div>
					</div>					
				</div>
			</div>
			<table id="purchase-datagrid"></table>
			<div id="purchaseEditWin" class="easyui-window" title="编辑" style="width:430px;height:450px" data-options="modal:true,closed:true,minimizable:false,maximizable:false">
				<div class="super-theme-example">
					<form id="purchaseEditForm">
						<input name="purchaseCode" type="hidden">
						<div class="form-item">
							<label for="" class="label-top">供应商：</label>
							<input name="supplierName" class="easyui-textbox" data-options="editable:false" style="width: 300px;" prompt="供应商...">
						</div>
						<div class="form-item">
							<label for="" class="label-top">采购链接：</label>
							<input name="purchaseUrl" class="easyui-textbox" style="width: 300px;" prompt="采购链接...">
						</div>
						<div class="form-item">
							<label for="" class="label-top">采购价：</label>
							<input name="purchasePrice" class="easyui-textbox" style="width: 300px;" prompt="采购价...">
						</div>
						<div class="form-item">
							<label for="" class="label-top">运费：</label>
							<input name="purchaseFreightPrice" class="easyui-textbox" style="width: 300px;" prompt="运费...">
						</div>
						<div class="form-item">
							<label for="" class="label-top">备注：</label>
							<input name="comments" class="easyui-textbox" style="width: 300px;" prompt="备注...">
						</div>
					</form>
					<div style="text-align: right; box-sizing: border-box;padding: 10px;">
						<a href="#" class="easyui-linkbutton" style="width: 80px;" onclick="$('#purchaseEditWin').window('close');">取消</a>
						<a href="#" class="easyui-linkbutton primary" style="width: 80px;" onclick="purchase.methods.editPurchaseSubimt();">保存</a>
					</div>
				</div>
			</div>
			<div id="purchase-skuDetais-window" class="easyui-window" title="详情/物流" style="width:1200px;" data-options="modal:true,closed:true,minimizable:false,maximizable:false">
				<div id="purchase-skuDetais-window-tab" class="easyui-tabs" data-options="border:false,plain:true" style="width:100%">
				    <div title="采购单商品详情">
						<table id="purchase-skuDetais-datagrid" style="height: 520px;width: 100%;"></table>
				    </div>
				    <div title="采购单物流详情">
						<table id="purchase-logistics-datagrid" style="height: 520px;width: 100%;"></table>
				    </div>
				</div>
			</div>
			<div id="purchaseDetailsEditWin" class="easyui-window" title="编辑" style="width:430px;height:380px" data-options="modal:true,closed:true,minimizable:false,maximizable:false">
				<div class="super-theme-example">
					<form id="purchaseDetailsEditForm">
						<input name="purchaseProductId" type="hidden">
						<input name="purchaseCode" type="hidden">
						<div class="form-item">
							<label for="" class="label-top">采购数量：</label>
							<input name="purchasedQuantity" class="easyui-textbox" style="width: 300px;" prompt="采购数量...">
						</div>
						<div class="form-item">
							<label for="" class="label-top">签收数量：</label>
							<input name="storagedQuantity" class="easyui-textbox" style="width: 300px;" prompt="签收数量...">
						</div>
						<div class="form-item">
							<label for="" class="label-top">取消数量：</label>
							<input name="cancelQuantity" class="easyui-textbox" style="width: 300px;" prompt="取消数量...">
						</div>
						<div class="form-item">
							<label for="" class="label-top">采购价：</label>
							<input name="purchasedPrice" class="easyui-textbox" style="width: 300px;" prompt="采购价...">
						</div>
					</form>
					<div style="text-align: right; box-sizing: border-box;padding: 10px;">
						<a href="#" class="easyui-linkbutton" style="width: 80px;" onclick="$('#purchaseDetailsEditWin').window('close');">取消</a>
						<a href="#" class="easyui-linkbutton primary" style="width: 80px;" onclick="purchase.methods.editPurchaseDetailsSubimt();">保存</a>
					</div>
				</div>
			</div>
			
			<div id="purchase-create-storehouse-Win" class="easyui-window" title="选择仓库" style="width:380px;height:220px" data-options="modal:true,closed:true,minimizable:false,maximizable:false">
				<div class="super-theme-example">
					<form id="purchase-create-storehouse-form">
						<div class="form-item">
							<label for="" class="label-top">仓库：</label>
							<input id="purchase-create-storehouseCombo" name="storehouseId" style="width:260px;">
						</div>
					</form>
					<div style="text-align: right; box-sizing: border-box;padding: 10px;">
						<a href="#" class="easyui-linkbutton" style="width: 80px;" onclick="$('#purchase-create-storehouse-Win').window('close');">取消</a>
						<a href="#" class="easyui-linkbutton primary" style="width: 80px;" onclick="purchase.methods.addPurchaseSubmit();">保存</a>
					</div>
				</div>
			</div>
			
			<div id="purchaseLogisticsEditWin" class="easyui-window" title="编辑" style="width:430px;height:320px" data-options="modal:true,closed:true,minimizable:false,maximizable:false">
				<div class="super-theme-example">
					<form id="purchaseLogisticsEditForm">
						<input name="purchaseCode" type="hidden">
						<input name="logisticId" type="hidden">
						<div class="form-item">
							<label for="" class="label-top">物流编号：</label>
							<input name="logisticCode" class="easyui-textbox" style="width: 300px;" prompt="物流编号...">
						</div>
						<div class="form-item">
							<label for="" class="label-top">物流公司：</label>
							<input name="logisticCompany" class="easyui-textbox" style="width: 300px;" prompt="物流公司...">
						</div>
						<div class="form-item">
							<label for="" class="label-top">物流编码：</label>
							<input name="carrierCode" class="easyui-textbox" style="width: 300px;" prompt="物流公司编码...">
						</div>
					</form>
					<div style="text-align: right; box-sizing: border-box;padding: 10px;">
						<a href="#" class="easyui-linkbutton" style="width: 80px;" onclick="$('#purchaseLogisticsEditWin').window('close');">取消</a>
						<a href="#" class="easyui-linkbutton primary" style="width: 80px;" onclick="purchase.methods.updatePurchaseLogisticsSbumit();">保存</a>
					</div>
				</div>
			</div>
		</div>
		<script type="text/javascript" src="dists/super/js/xlsx.full.min.js" ></script>
		<script type="text/javascript">
			var purchase = {
				datas : {
				},
				methods: {
					initToobarCombo: function(){
						$('#purchase-supplier-combo').combobox({
						    url: commonConfig.shopUrlPrefix() + '/supplier/combobox',
						    valueField: 'id',
						    textField: 'text'
						});
						$('#purchase-storehouseCombo').combobox({
						    url: commonConfig.mgUrlPrefix() + '/admin/storehouse/combo',
						    valueField: 'id',
						    textField: 'text'
						});
					},
					initTimeSelect: function(){
						$('#purchase-datepicker').daterangepicker($.extend(true, {} , globalDaterangepickerOptions));
					},
					initDatagrid: function(){
						
						var datagridColumns = [
							{field:'purchaseCode',title:'采购单号',width:100,align:'center',formatter: function(value,row,index){
									return '<a onclick="purchase.methods.showPurchaseDetails('+index+');">'+value+'</a>';
							}},
							{field:'supplierName',title:'采购来源',width:80,align:'center'},
							{field:'skus',title:'采购单详情',width:200,align:'center', formatter: function(value,row,index){
								var _html = '<ul class="skuDetails">' ; 
								$.each(row.purchaseProductSearchDTOs, function(index , productSearchDTO) {
									_html +='	<li>'+
											'		<img class="img" src="'+ productSearchDTO.productSkuImage +'" />'+
											'		<span class="productId">'+ productSearchDTO.productSkuBarcode +'(x'+ productSearchDTO.purchasedQuantity +')</span>'+
											'		<span class="title">'+ productSearchDTO.productTitle +'</span>'+
											'		<span class="skuName">'+ productSearchDTO.productSkuName +'</span>'+
											'	</li>';
									if(index == 5) {
										_html += '<li style="height: initial;"><span>...</span></li>'
										return false;
									}
								});
								_html += '</ul>';
								return _html ; 
							}},
							{field:'storehouseName',title:'仓库',width:60,align:'center'},
							{field:'purchasePrice',title:'采购价',width:60,align:'center',formatter:function(value,row,index){return '<span>'+ row.purchasePrice +'</span><br/><span class="small-opacity-8">(运费:'+ row.purchaseFreightPrice +')</span>';}},
							{field:'quantity',title:'采购/签收/取消',width:80,align:'center',formatter:function(value,row,index){return '<span>'+ row.purchasedTotalQuantity +'</span> / <span>'+ row.storagedTotalQuantity +'</span> / <span>'+ row.cancelTotalQuantity +'</span>';}},
							{field:'statusName',title:'状态',width:60,align:'center'},
							{field:'comments',title:'备注',width:100,align:'center'},
							{field:'logistics',title:'采购单物流',width:120,align:'center', formatter: function(value,row,index){
								var _html = '<ul class="skuDetails">' ; 
								$.each(row.purchaseLogisticsSearchDTOs, function(index , tmp) {
									_html +='	<li style="height: initial;">'+
											'		<span>'+ tmp.logisticCompany +': '+ tmp.logisticCode +'</span>'+
											'	</li>';
									if(index == 5) return false;
								});
								_html += '</ul>';
								return _html ; 
							}},
							{field:'createdAt',title:'创建时间',width:100,align:'center',formatter:function(value,row,index){return FormatDate(value);}},
							{field:'options',title:'操作',width:80,align:'center', formatter: function(value,row,index){
								return '<div class="row-edit-group">' +
									        ((row.status == 0 || row.status == 10) ? '<a onclick="purchase.methods.editPurchase('+index+')">编辑</a>' : '') + 
									        ((row.status == 0 || row.status == 10) ? '<a onclick="purchase.methods.deletePurchase('+index+')">删除</a>' : '') +
									        '<a onclick="purchase.methods.exportPurchaseDetails('+index+')">导出明细</a>' +
									   '</div>';
							}}
						] ;
						
						var cRoles = JSON.parse(localStorage.getItem('roles')) ; 
						if(cRoles.length == 1 && cRoles[0] == "storehouse"){
							datagridColumns.splice(1,1);
							datagridColumns.splice(3,1);
						}
						
						$('#purchase-datagrid').datagrid({
							height: $(document).height() - 200,
						    url: commonConfig.mgUrlPrefix() + '/admin/purchase/list',
						    queryParams: {
								begainTime: timestamp($('#purchase-datepicker').val().substring(0, 19)),
								endTime: timestamp($('#purchase-datepicker').val().substring(22))
							},
						    columns:[datagridColumns]
						});
					},
					initDatagridQueryParams: function(){
						var params = $('#purchaseDatagridQueryParams').serializeArray();
						var queryParams = {};
						$.each(params , function(index , param){
						     queryParams[param.name] = param.value;
						})
						var time = $('#purchase-datepicker').val();
						queryParams.begainTime = timestamp(time.substring(0, 19));
						queryParams.endTime = timestamp(time.substring(22));
						
						queryParams.purchaseCode = queryParams.purchaseCode.replace(/[\r\n，]/g,",");
						queryParams.logisticCode = queryParams.logisticCode.replace(/[\r\n，]/g,",");
						
						$.each($('#purchase-supplier-combo').combobox('getData') , function(index , _data){    
							if(_data.id && _data.id != '' && _data.id == queryParams.supplierId){
								queryParams.supplierName = _data.text ;
       							return false;
    						}
						});
						return queryParams;
					},
					queryDatagrid: function(){
						$('#purchase-datagrid').datagrid('reload',purchase.methods.initDatagridQueryParams());
					},
					addPurchase: function(e){
						var files = $(e).context.files
						var fileReader = new FileReader()
						if (files.length) {
							fileReader.onload = function (ev) {
								try {
									var workbook = XLSX.read(ev.target.result, {type: 'binary'});
								} catch (e) {
									$.messager.alert('提示',e,'error');
									return
								}
								// 创建收货单提交
								purchase.methods.addPurchaseNext(XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]));
								e.value = '' // 清空
							}
							fileReader.readAsBinaryString(files[0]);
						}
					},
					addPurchaseNext: function(paramList){
						var list = [] // 处理后的数据
						var index = -1 // 当前收货单单下标
						for (let i = 1; i < paramList.length; i++) {
							if (paramList[i]['采购单号']) {
								// push收货单
								list.push({
									'purchaseCode': paramList[i]['采购单号'],
									'supplierName': paramList[i]['供应商名称'],
									'purchaseUrl': paramList[i]['采购链接'],
									'purchasePrice': paramList[i]['采购总价'],
									'purchaseFreightPrice': paramList[i]['运费'],
									'comments': paramList[i]['备注'],
									'purchaseProductCreateRequests': [{
										'productId': paramList[i]['商品明细'],
										'productTitle': paramList[i]['__EMPTY'],
										'productSkuId': paramList[i]['__EMPTY_1'],
										'productSkuBarcode': paramList[i]['__EMPTY_2'],
										'productSkuName': paramList[i]['__EMPTY_3'],
										'productSkuImage': paramList[i]['__EMPTY_4'],
										'purchasedPrice': paramList[i]['__EMPTY_5'],
										'purchasedQuantity': paramList[i]['__EMPTY_6']
									}]
								})
								index++
							} else {
								// push商品和物流
								if (paramList[i]['商品明细']) {
									list[index]['purchaseProductCreateRequests'].push({
										'productId': paramList[i]['商品明细'],
										'productTitle': paramList[i]['__EMPTY'],
										'productSkuId': paramList[i]['__EMPTY_1'],
										'productSkuBarcode': paramList[i]['__EMPTY_2'],
										'productSkuName': paramList[i]['__EMPTY_3'],
										'productSkuImage': paramList[i]['__EMPTY_4'],
										'purchasedPrice': paramList[i]['__EMPTY_5'],
										'purchasedQuantity': paramList[i]['__EMPTY_6']
									})
								}
							}
						}
						if(list.length == 0){
							$.messager.alert('提示','上传内容为空','error');
							return ;
						}
						
						purchase.datas.createPurchaseLists = list ; 
						
						$('#purchase-create-storehouse-Win').window('open');
						$('#purchase-create-storehouseCombo').combobox({
						    url: commonConfig.mgUrlPrefix() + '/admin/storehouse/combo',
						    valueField: 'id',
						    textField: 'text',
						    onLoadSuccess: function(){
						    	var _datas = $('#purchase-create-storehouseCombo').combobox('getData');
								if(_datas.length > 0)$('#purchase-create-storehouseCombo').combobox('select' , _datas[0].id);
						    }
						});
					},
					addPurchaseSubmit: function(){
						var _storehouseId = $('#purchase-create-storehouseCombo').combobox('getValue') ; 
						if(_storehouseId == ''){
							$.messager.alert('提示','仓库不能为空','error');
							return ;
						}
						
						$.each(purchase.datas.createPurchaseLists, function(index , _tmp) {
							_tmp.storehouseId = _storehouseId ; 
						});
						
						requestBodyServer(commonConfig.mgUrlPrefix() + '/admin/purchase/create' , 'POST', purchase.datas.createPurchaseLists).then((response) => {
							if (response.code == 1) {
								//在这里需要注意操作的情况
								$('#purchase-create-storehouse-Win').window('close');
								if(response.datas && response.datas.length > 0){
									showErrorMsgs(response.datas , [[{field:'purchaseCode',title:'采购单号',width:60,align:'center'},{field:'errorMsg',title:'错误信息',width:60,align:'center'}]]);
								}else{
									showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求成功...');
									$('#purchase-datagrid').datagrid('reload');
								}
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					addPurchaseLogistics: function(e){
						var files = $(e).context.files
						var fileReader = new FileReader()
						if (files.length) {
							fileReader.onload = function (ev) {
								try {
									var workbook = XLSX.read(ev.target.result, {type: 'binary'});
								} catch (e) {
									$.messager.alert('提示',response.message,'error');
									return
								}
								// 创建收货单提交
								purchase.methods.addPurchaseLogisticsNext(XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]]));
								e.value = '' // 清空
							}
							fileReader.readAsBinaryString(files[0]);
						}
					},
					addPurchaseLogisticsNext: function(paramList){
						var list = [] // 处理后的数据
						for (let i = 0; i < paramList.length; i++) {
							if (paramList[i]['采购单号']) {
								// push收货单
								list.push({
									'purchaseCode': paramList[i]['采购单号'],
									'logisticCode': paramList[i]['物流单号'],
									'logisticCompany': paramList[i]['物流公司'],
									'carrierCode': paramList[i]['物流公司编码']
								})
							}
						}
						if(list.length == 0){
							$.messager.alert('提示','上传内容为空','error');
							return ;
						}
						requestBodyServer(commonConfig.mgUrlPrefix() + '/admin/purchase/logistics' , 'POST', list).then((response) => {
							if (response.code == 1) {
								//在这里需要注意操作的情况
								if(response.datas && response.datas.length > 0){
									showErrorMsgs(response.datas , [[{field:'logisticCode',title:'物流单号',width:60,align:'center'},{field:'errorMsg',title:'错误信息',width:60,align:'center'}]]);
								}else{
									showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求成功...');
									$('#purchase-datagrid').datagrid('reload');
								}
							}else {
								$.messager.alert('提示',response.message,'error');
							}
							
						}).catch((error) => {
							console.log(error)
						});
					},
					asyncPurchase: function(index){
						requestServer(commonConfig.mgUrlPrefix() + '/admin/purchase/' + $('#purchase-datagrid').datagrid('getRows')[index].purchaseCode + '/async', 'PUT').then((response) => {
							if (response.code == 1) {
								showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求...');
								purchase.methods.queryDatagrid();
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					storagePurchase: function(pindex, index){
						var _prow = $('#purchase-datagrid').datagrid('getRows')[pindex] ; 
						var _row = $('#purchase-skuDetais-datagrid').datagrid('getRows')[index] ; 
						
						$.messager.prompt('提示', '收货数量: ', function(r){
				            if (r){
				            	var _quantity = parseInt(r);
				            	if(_quantity > 0){
				            		var _params = {
				            			batchNumber: _prow.purchaseCode , 
				            			productSkuBarcode: _row.productSkuBarcode,
				            			quantity: _quantity
				            		}
				            		requestBodyServer(commonConfig.mgUrlPrefix() + '/admin/purchase/storage' , 'POST' , [_params]).then((response) => {
										if (response.code == 1) {
											
											purchase.methods.queryDatagrid();
											$('#purchase-skuDetais-datagrid').datagrid('reload');
											
											if(response.datas && response.datas.length > 0){
												showErrorMsgs(response.datas , [[{field:'productSkuBarcode',title:'商品编码',width:60,align:'center'},{field:'errorMsg',title:'错误信息',width:60,align:'center'}]]);	
											}else{
												showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求成功...');
											}
											
										}else {
											$.messager.alert('提示',response.message,'error');
										}
									}).catch((error) => {
										console.log(error)
									});
				            	}else{
				            		$.messager.alert('提示', '数量不正确' ,'error');
				            	}
				            }
				        });
				        var _maxQuantity = (_row.purchasedQuantity - _row.storagedQuantity) ;
				        $('.messager-input').numberspinner({value: _maxQuantity, min: 1, max: _maxQuantity, width: 135});
					},
					editPurchase: function(index){
						$('#purchaseEditWin').window('open');
						$('#purchaseEditForm').form('clear');
						$('#purchaseEditForm').form('load' , $('#purchase-datagrid').datagrid('getRows')[index]);
					},
					editPurchaseSubimt: function(){
						var _formData = $('#purchaseEditForm').serializeJson() ;
						requestBodyServer(commonConfig.mgUrlPrefix() + '/admin/purchase/' , 'PUT', _formData).then((response) => {
							if (response.code == 1) {
								showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求成功...');
								$('#purchaseEditWin').window('close');
								purchase.methods.queryDatagrid();
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					},
					deletePurchase: function(index){
						$.messager.confirm('提示', '确定删除?', function(r){
							if (r){
								requestServer(commonConfig.mgUrlPrefix() + '/admin/purchase/' + $('#purchase-datagrid').datagrid('getRows')[index].purchaseCode, 'DELETE').then((response) => {
									if (response.code == 1) {
										showMessage('<i class="fa fa-info-circle"></i>&nbsp; 删除成功...');
										purchase.methods.queryDatagrid();
									}else {
										$.messager.alert('提示',response.message,'error');
									}
								}).catch((error) => {
									console.log(error)
								});
							}
						});
					},
					exportPurchaseDetails: function(index){
						exportExcel(commonConfig.mgUrlPrefix() + '/admin/purchase/' + $('#purchase-datagrid').datagrid('getRows')[index].purchaseCode + '/products/export');
					},
					showPurchaseDetails: function(pindex , status){
						$('#purchase-skuDetais-window').window('open');
						$('#purchase-skuDetais-window-tab').tabs('select',0);
						var _prow = $('#purchase-datagrid').datagrid('getRows')[pindex] ; 
						
						$('#purchase-skuDetais-datagrid').datagrid({
							url: commonConfig.mgUrlPrefix() + '/admin/purchase/'+_prow.purchaseCode+'/products',
							pagination:false,
						    columns:[[
						    	{field:'productId',title:'产品ID',width:80,align:'center',formatter:function(value,row,index){return '<span>'+row.productId+'</span><br/><span style="opacity: 0.8;">('+row.productSkuBarcode+')</span>';}},
						    	{field:'productTitle',title:'产品名称',width:120,align:'center',formatter:function(value,row,index){return '<span>'+row.productTitle+'</span><br/><span style="opacity: 0.8;">('+row.productSkuName+')</span>';}},
						    	{field:'productSkuImage',title:'产品图片',width:60,align:'center',formatter:function(value,row,index){return '<img class="td-img" src="'+ value +'">';}},
								{field:'purchasedPrice',title:'采购价',width:60,align:'center'},
								{field:'purchaseUrl',title:'采购链接',width:120,align:'center',formatter:function(value,row,index){return _prow.purchaseUrl;}},
								{field:'quantity',title:'采购/签收/取消',width:100,align:'center',formatter:function(value,row,index){return '<span>'+row.purchasedQuantity+'</span> / <span>'+row.storagedQuantity+'</span> / <span>'+row.cancelQuantity+'</span>';}},
								{field:'options',title:'操作',width:80,align:'center', formatter: function(value,row,index){
									return '<div class="row-edit-group">' +
										        '<a onclick="purchase.methods.editPurchaseDetails('+ pindex +' , '+ index +')">编辑</a>' + 
										   '</div>';
								}}
						    ]]
						});
						
						$('#purchase-logistics-datagrid').datagrid({
							url: commonConfig.mgUrlPrefix() + '/admin/purchase/'+_prow.purchaseCode+'/logistics',
							pagination:false,
							toolbar: [
								{
									iconCls: 'fa fa-plus',
									text: '新增物流',
									handler: function(){
										console.log(pindex);
										console.log(_prow);
										$('#purchaseLogisticsEditWin').window('open');
										$('#purchaseLogisticsEditForm').form('clear');
										$('#purchaseLogisticsEditForm').form('load' , {purchaseCode: _prow.purchaseCode});
									}
								}
							],
						    columns:[[
						    	{field:'logisticCode',title:'物流单号',width:80,align:'center'},
						    	{field:'logisticCompany',title:'物流公司',width:120,align:'center'},
						    	{field:'carrierCode',title:'物流公司代码',width:60,align:'center'},
								{field:'options',title:'操作',width:80,align:'center', formatter: function(value,row,index){
									if(_prow.status == 0 || _prow.status == 10){
										return '<div class="row-edit-group">' +
											        '<a onclick="purchase.methods.updatePurchaseLogistics('+ pindex +' , '+ index +')">编辑</a>' + 
											        '<a onclick="purchase.methods.deletePurchaseLogistics('+ pindex +' , '+ index +')">删除</a>' + 
											   '</div>';
									}
									return '' ; 
								}}
						    ]]
						});
					},
					printProductBarcode: function(index){
						var _formData = $('#purchase-skuDetais-datagrid').datagrid('getRows')[index];
						tools.printProductBarcode({
							product_id: _formData.productId,
							product_sku_name: _formData.productSkuName,
							product_title: _formData.productTitle,
							product_sku_barcode: _formData.productSkuBarcode
						})
					},
					updatePurchaseLogistics: function(pindex , index){
						$('#purchaseLogisticsEditWin').window('open');
						$('#purchaseLogisticsEditForm').form('clear');
						var _formData = $('#purchase-logistics-datagrid').datagrid('getRows')[index];
						var _pformData = $('#purchase-datagrid').datagrid('getRows')[pindex] ; 
						_formData.purchaseCode = _pformData.purchaseCode ; 
						$('#purchaseLogisticsEditForm').form('load' , _formData);
					},
					updatePurchaseLogisticsSbumit: function(){
						var _formData = $('#purchaseLogisticsEditForm').serializeJson();
						if(!_formData.logisticId || _formData.logisticId == ''){
							requestBodyServer(commonConfig.mgUrlPrefix() + '/admin/purchase/logistics' , 'POST', [_formData]).then((response) => {
								if (response.code == 1) {
									//在这里需要注意操作的情况
									if(response.datas && response.datas.length > 0){
										showErrorMsgs(response.datas , [[{field:'logisticCode',title:'物流单号',width:60,align:'center'},{field:'errorMsg',title:'错误信息',width:60,align:'center'}]]);
									}else{
										showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求成功...');
										$('#purchase-logistics-datagrid').datagrid('reload');
									}
								}else {
									$.messager.alert('提示',response.message,'error');
								}
								
							}).catch((error) => {
								console.log(error)
							});
						}else{
							_formData.newLogisticCode = _formData.logisticCode ;
							requestBodyServer(commonConfig.mgUrlPrefix() + '/admin/purchase/logistics' , 'PUT', _formData).then((response) => {
								if (response.code == 1) {
									showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求成功...');
									$('#purchaseLogisticsEditWin').window('close');
									$('#purchase-logistics-datagrid').datagrid('reload');
								}else {
									$.messager.alert('提示',response.message,'error');
								}
							}).catch((error) => {
								console.log(error)
							});
						}
					},
					deletePurchaseLogistics: function(pindex , index){
						$.messager.confirm('提示', '确定删除?', function(r){
							if (r){
								requestServer(commonConfig.mgUrlPrefix() + '/admin/purchase/logistics/' + $('#purchase-logistics-datagrid').datagrid('getRows')[index].logisticId, 'DELETE').then((response) => {
									if (response.code == 1) {
										showMessage('<i class="fa fa-info-circle"></i>&nbsp; 删除成功...');
										$('#purchase-logistics-datagrid').datagrid('reload');
									}else {
										$.messager.alert('提示',response.message,'error');
									}
								}).catch((error) => {
									console.log(error)
								});
							}
						});
					},
					editPurchaseDetails: function(pindex , index){
						$('#purchaseDetailsEditWin').window('open');
						$('#purchaseDetailsEditForm').form('clear');
						var _pformData = $('#purchase-datagrid').datagrid('getRows')[pindex] ; 
						var _formData = $('#purchase-skuDetais-datagrid').datagrid('getRows')[index] ;
						_formData.purchaseProductId = _formData.id ; 
						_formData.purchaseCode = _pformData.purchaseCode ; 
						$('#purchaseDetailsEditForm').form('load' , _formData);
					},
					editPurchaseDetailsSubimt: function(){
						var _formData = $('#purchaseDetailsEditForm').serializeJson();
						requestBodyServer(commonConfig.mgUrlPrefix() + '/admin/purchase/'+ _formData.purchaseCode +'/products' , 'PUT', _formData).then((response) => {
							if (response.code == 1) {
								showMessage('<i class="fa fa-info-circle"></i>&nbsp; 请求成功...');
								$('#purchaseDetailsEditWin').window('close');
								$('#purchase-skuDetais-datagrid').datagrid('reload');
							}else {
								$.messager.alert('提示',response.message,'error');
							}
						}).catch((error) => {
							console.log(error)
						});
					}
				},
				init : function(){
					purchase.methods.initToobarCombo();
					purchase.methods.initTimeSelect();
					purchase.methods.initDatagrid();
				}
			}
			purchase.init();
		</script>
	</body>
</html>
